package sskj.regulatory.presentation.screen.authentication.projectdepartment

import android.annotation.SuppressLint
import android.support.v7.widget.LinearLayoutManager
import android.text.*
import android.text.style.AbsoluteSizeSpan
import android.view.View
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter
import com.jude.easyrecyclerview.decoration.DividerDecoration
import com.qmuiteam.qmui.util.QMUIDirection
import com.qmuiteam.qmui.util.QMUIViewHelper.*
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.vondear.rxtools.RxDataTool
import com.vondear.rxtools.RxImageTool
import kotlinx.android.synthetic.main.fragment_login.view.*
import kotlinx.android.synthetic.main.fragment_projectdept_auth.view.*
import sskj.regulatory.R
import sskj.regulatory.data.response.eng.EngResponse
import sskj.regulatory.data.response.session.BingDingResponse
import sskj.regulatory.data.response.session.IndexDataResponse
import sskj.regulatory.domain.entity.user.BingDingEntity
import sskj.regulatory.presentation.adapter.ProjectDeptRecyclerArrayAdapter
import sskj.regulatory.presentation.base_mvp.base.BaseFragment
import sskj.regulatory.presentation.constans.Constans
import sskj.regulatory.presentation.utils.extensions.hide
import javax.inject.Inject

class ProjectDeptFragment : BaseFragment<ProjectDeptContract.View, ProjectDeptContract.Presenter>(), ProjectDeptContract.View {


    override fun showBingDing(name: String, content: String, engResponse: EngResponse) {
        mCacheView.pdNameTv.text = name
        mCacheView.pdContentTv.text = content
        when (mAdapter.allData.isEmpty()) {
            true -> {
                mAdapter.addAll(engResponse.data)
                mAdapter.stopMore()
            }
        }
    }


    @Inject
    lateinit var mPresenter: ProjectDeptPresenter

    private val mAdapter: ProjectDeptRecyclerArrayAdapter = ProjectDeptRecyclerArrayAdapter(context)

    override fun injectDependencies() = activityComponent.inject(this)

    override val layoutResId: Int = R.layout.fragment_projectdept_auth

    override fun onBackPressed(): Boolean = true

    override fun initPresenter() = mPresenter

    override fun onFetchTransitionConfig(): TransitionConfig {
        return POP_TRANSITION_CONFIG
    }

    override fun initView() {

        mCacheView.authLogin.visibility = View.GONE
        mCacheView.authContent.visibility = View.GONE
        initTopBar()
        initEvent()
        initHitView()
        initRecylerView()
    }

    override fun initOk(bingDingEntity: BingDingEntity?) {
        when (bingDingEntity) {
            null -> {
                mCacheView.authLogin.visibility = View.VISIBLE
                mCacheView.authContent.visibility = View.GONE
                mCacheView.pdBingdingBtn.visibility = View.VISIBLE
                mCacheView.pdCBingdingBtn.visibility = View.GONE
                mCacheView.pdTopBar.removeAllRightViews()
                mCacheView.pdTopBar.removeAllLeftViews()
                mCacheView.pdTopBar.addRightTextButton("取消", R.id.topbar_right_cancel_button).setOnClickListener { popBackStack() }
            }
            else -> {
                mCacheView.authLogin.visibility = View.GONE
                mCacheView.authContent.visibility = View.VISIBLE
                mCacheView.pdBingdingBtn.visibility = View.GONE
                mCacheView.pdCBingdingBtn.visibility = View.VISIBLE
                mCacheView.pdTopBar.removeAllRightViews()
                mCacheView.pdTopBar.removeAllLeftViews()
                mCacheView.pdTopBar.addLeftBackImageButton().setOnClickListener { popBackStack() }
                mCacheView.pdTopBar.addRightTextButton("修改", R.id.topbar_right_cancel_button).setOnClickListener {
                    popBackStack()
                }
            }
        }
    }

    private fun initRecylerView() {

        mCacheView.pdEasyRecyclerView.setLayoutManager(LinearLayoutManager(context,
                LinearLayoutManager.VERTICAL, false))

        val itemDecoration = DividerDecoration(R.color.qmui_config_color_25_pure_black, RxImageTool.dip2px(0.4f), RxImageTool.dip2px(5f), RxImageTool.dip2px(5f))//颜色 & 高度 & 左边距 & 右边距

        itemDecoration.setDrawLastItem(false)

        itemDecoration.setDrawHeaderFooter(false)

        mCacheView.pdEasyRecyclerView.addItemDecoration(itemDecoration)

        mCacheView.pdEasyRecyclerView.setAdapterWithProgress(mAdapter)

        mCacheView.pdEasyRecyclerView.setRefreshing(false)

        mAdapter.setMore(R.layout.view_more, object : RecyclerArrayAdapter.OnMoreListener {

            override fun onMoreShow() {

            }

            override fun onMoreClick() {

            }
        })


        mAdapter.setNoMore(R.layout.view_no_more)

    }

    private fun initEvent() {

        mCacheView.etPdMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                if (!TextUtils.isEmpty(s) && mCacheView.ivCleanPdPhone.visibility == View.GONE) {
                    mCacheView.ivCleanPdPhone.visibility = View.VISIBLE
                } else if (TextUtils.isEmpty(s)) {
                    mCacheView.ivCleanPdPhone.visibility = View.GONE
                }
            }
        })
        mCacheView.etPdPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                if (!TextUtils.isEmpty(s) && mCacheView.ivCleanPdPassword.visibility == View.GONE) {
                    mCacheView.ivCleanPdPassword.visibility = View.VISIBLE
                } else if (TextUtils.isEmpty(s)) {
                    mCacheView.ivCleanPdPassword.visibility = View.GONE
                }
                if (s.isEmpty()) {
                    return
                }
            }
        })


        mCacheView.ivCleanPdPhone.setOnClickListener { mCacheView.etPdMobile.setText("") }
        mCacheView.ivCleanPdPassword.setOnClickListener { mCacheView.etPdPassword.setText("") }

        mCacheView.pdLoginBtn.setOnClickListener { mPresenter.auth(mCacheView.etPdMobile.text.toString(), mCacheView.etPdPassword.text.toString()) }
        mCacheView.pdBingdingBtn.setOnClickListener { mPresenter.bingDing(mCacheView.etPdMobile.text.toString(), mCacheView.etPdPassword.text.toString()) }
        mCacheView.pdCBingdingBtn.setOnClickListener { mPresenter.delBingDing() }
    }

    private fun initTopBar() {
        mCacheView.pdTopBar.setTitle("项目部认证")
        mCacheView.pdTopBar.setBackgroundDividerEnabled(false)

    }

    @SuppressLint("ResourceAsColor")
    private fun initHitView() {
        var ss = SpannableString("项目部用户名")
        val ass = AbsoluteSizeSpan(14, true)

        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mCacheView.etPdMobile.hint = SpannedString(ss);
        mCacheView.etPdMobile.setHintTextColor(R.color.qmui_config_color_50_pure_black)

        ss = SpannableString("密码")
        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        mCacheView.etPdPassword.hint = SpannedString(ss);
        mCacheView.etPdPassword.setHintTextColor(R.color.qmui_config_color_50_pure_black)

    }


    override fun bingDingOk() {
        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                .setTipWord("绑定成功")
                .create()
        activity.tipDialog?.show()

        view?.postDelayed({
            activity.tipDialog?.dismiss()
            mPresenter.indexData()
        }, 1500)
    }

    override fun delBingDingOk() {
        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                .setTipWord("解绑成功")
                .create()
        activity.tipDialog?.show()

        fadeIn(mCacheView.authLogin, 300, object : AnimationListener {
            override fun onAnimationEnd(p0: Animation?) {
                mCacheView.authLogin.visibility = View.VISIBLE
                sideOutContentView()
            }

            override fun onAnimationRepeat(p0: Animation?) {}
            override fun onAnimationStart(p0: Animation?) {}
        }, true)


        view?.postDelayed({
            activity.tipDialog?.dismiss()
        }, 1500)
    }


    override fun authOk(eng: EngResponse, username: String) {

        when (mCacheView.authLogin.visibility) {
            View.GONE -> {
                sideInContentView(eng, username)
            }
            View.VISIBLE -> {
                fadeOut(mCacheView.authLogin, 300, object : AnimationListener {
                    override fun onAnimationEnd(p0: Animation?) {
                        mCacheView.authLogin.visibility = View.GONE
                        sideInContentView(eng, username)
                    }

                    override fun onAnimationRepeat(p0: Animation?) {}
                    override fun onAnimationStart(p0: Animation?) {}
                }, true)
            }
        }
    }

    private fun sideOutContentView() {
        slideOut(mCacheView.authContent, 300, object : AnimationListener {
            override fun onAnimationEnd(p0: Animation?) {
                mCacheView.authContent.visibility = View.GONE
            }

            override fun onAnimationRepeat(p0: Animation?) {}
            override fun onAnimationStart(p0: Animation?) {}
        }, true, QMUIDirection.TOP_TO_BOTTOM)
    }

    private fun sideInContentView(eng: EngResponse, username: String) {
        slideIn(mCacheView.authContent, 300, object : AnimationListener {
            override fun onAnimationEnd(p0: Animation?) {

                showBingDing(RxDataTool.hideMobilePhone4(username), "你共参与了${eng.data.size}个工程。", eng)
            }

            override fun onAnimationRepeat(p0: Animation?) {}
            override fun onAnimationStart(p0: Animation?) {
                mCacheView.authContent.visibility = View.VISIBLE
            }
        }, true, QMUIDirection.BOTTOM_TO_TOP)
    }

    override fun showLoading() {
        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create()
        activity.tipDialog?.show()
    }

    override fun hideLoading() {
        activity.tipDialog?.dismiss()
    }

    override fun showTipDialogError(message: String?) {
        activity.tipDialog?.dismiss()

        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                .setTipWord(message)
                .create()
        activity.tipDialog?.show()

        view?.postDelayed({
            activity.tipDialog?.dismiss()
        }, 1000)
    }

    override fun showError(message: String?) {
        hideLoading()
        QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("错误提示")
                .setMessage(message)
                .addAction("确定") { dialog, _ -> dialog.dismiss() }
                .create(R.style.QMUI_Dialog).show()
    }

}